//
//  ViewController.m
//  GGFriendTable
//
//  Created by lisheng on 16/3/13.
//  Copyright © 2016年 鬼谷传人. All rights reserved.
//

#import "ViewController.h"
#import "GGSort.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating>
{
    BOOL shouldShowSearchResults;
}
/**
 *  display datasource , depend on Bool(shouldShowSearchResults) to choose show
 *  original table or search table
 */
@property (nonatomic, strong) UITableView * tableView;
/**
 *   search controller provides a UISearchBar
 */
@property (nonatomic, strong) UISearchController * searchController;
/**
 *  contain all source data to display
 */
@property (nonatomic, strong) NSArray * dataSourceArray;
/**
 *  contain the search results data
 */
@property (nonatomic, strong) NSMutableArray * searchResultsArray;

/// dataSourceDictionary like as {"A":["a","aa"],"B":["b","bb"],...}
@property (nonatomic, strong) NSDictionary * dataSourceDictionary; 

/**
 *  table section title array
 */
@property (nonatomic, strong) NSArray * sectionIndexTitleArray;
/**
 *  nick name store array
 */
@property (nonatomic, strong) NSMutableDictionary * nickNameDictionary;

@end

@implementation ViewController


#pragma mark - lazyLoad
- (NSMutableDictionary *)nickNameDictionary {
    if (!_nickNameDictionary) {
        _nickNameDictionary = [[NSMutableDictionary alloc] initWithCapacity:0];
        for (NSString * value in self.dataSourceArray) {
            [_nickNameDictionary setObject:value forKey:[GGSort getPinYinByString:value]];
        }
    }
    return _nickNameDictionary;
}

#warning 数据源,只需要修改这里即可
- (NSArray *)dataSourceArray {
    if (!_dataSourceArray) {
        _dataSourceArray = @[@"Apple🍎",@"宝贝",@"宝宝的世界🐷",@"anyone",@"海绵宝宝",@"罗依琳❤️",@"月光",@"牛宝宝",@"姿美人",@"海大力"];
    }
    return _dataSourceArray;
}
#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    shouldShowSearchResults = NO;
    
    [self configureTableView];
    
    [self configureSearchController];
    
    [GGSort sortArray:self.dataSourceArray completionHandle:^(NSArray *keysArray, NSDictionary *dic) {
        self.sectionIndexTitleArray = keysArray;
        self.dataSourceDictionary = dic;
    }];
    
}
- (void)configureTableView {
    _tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
}

- (void)configureSearchController {
    
    // Pass nil if you wish to display search results in the same view that you are searching.
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    _searchController.searchResultsUpdater= self;
    _searchController.searchBar.delegate = self;
    
    self.tableView.tableHeaderView = _searchController.searchBar;
    
}

#pragma mark - UITableViewDataSource, Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return !shouldShowSearchResults ? self.sectionIndexTitleArray.count : 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (shouldShowSearchResults) {
        return self.searchResultsArray.count;
    }
    
    NSString * key = self.sectionIndexTitleArray[section];
    
    NSArray * valuesArray = self.dataSourceDictionary[key];
    
    return valuesArray.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * cellId = @"cell_identifier";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    if (shouldShowSearchResults) {
        cell.textLabel.text = self.searchResultsArray[indexPath.row];
    }else {
        NSString * key = self.sectionIndexTitleArray[indexPath.section];
        
        NSArray * valuesArray = [GGSort sortedArray:self.dataSourceDictionary[key]];
        
        cell.textLabel.text = valuesArray[indexPath.row];
    }
    
    return cell;
}
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (shouldShowSearchResults) {
        return nil;
    }
    return self.sectionIndexTitleArray;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (shouldShowSearchResults) {
        return nil;
    }
    return self.sectionIndexTitleArray[section];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 20.0f;
    }
    return 10.0f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (shouldShowSearchResults) {
        // search table
    }else {
        // original table
    }
}
#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    shouldShowSearchResults = YES;
    [self.tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    shouldShowSearchResults = NO;
    [self.tableView reloadData];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    if (!shouldShowSearchResults) {
        shouldShowSearchResults = YES;
        [self.tableView reloadData];
    }
    [self.searchController.searchBar resignFirstResponder];
}

#pragma mark - UISearchResultUpadating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString * searchString = searchController.searchBar.text;
    NSPredicate * predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",searchString];
    
    self.searchResultsArray = [[self.dataSourceArray filteredArrayUsingPredicate:predicate] mutableCopy];
    NSString * string = [searchString lowercaseString];
    
    for (NSString * key in [self.nickNameDictionary allKeys]) {
        
        if ([key hasPrefix:string]) {
            NSArray * array = self.dataSourceDictionary[[string uppercaseString]];
            for (NSString * name in array) {
                [self.searchResultsArray addObject:name];
            }
        }
    }
    self.searchResultsArray = [[GGSort sortedArray:self.searchResultsArray] mutableCopy];
    
    [self.tableView reloadData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
